package com.cjd.common.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.FileProvider
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2017-04-14.
 * description
 */
object ImageHandleUtils {

    val FILE_PROVIDER = "com.cjd.common.fileprovider"

    /**
     * 拍照
     *
     * @param activity
     * @param imagePath
     * @param requestCode
     */
    fun takePhoto(activity: Activity, imagePath: File, requestCode: Int) {
        //用于启动相机
        val takePhotoIntent = Intent()
        var imageUri: Uri? = null

        if (!imagePath.parentFile.exists()) {
            imagePath.parentFile.mkdirs()
        }

        if (Build.VERSION.SDK_INT >= 24) {
            //Android 7.0以上，将file转换为一个封装过的uri，否则会抛出FileUriExposedException异常
            //FileProvider是一种特殊内容提供器，选择性将封装过的uri共享给外部，需要在Manifest注册
            imageUri = FileProvider.getUriForFile(activity, FILE_PROVIDER, imagePath)
            //对目标应用临时授权该Uri所代表的文件
            takePhotoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        } else {
            //Android 7.0以下，直接将file转换为uri，为图片的本地真实路径
            imageUri = Uri.fromFile(imagePath)
        }
        takePhotoIntent.action = MediaStore.ACTION_IMAGE_CAPTURE
        //指定图片输出地址
        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
        activity.startActivityForResult(takePhotoIntent, requestCode)
    }

    /**
     * 打开相册
     */
    fun openAlum(activity: Activity, requestCode: Int) {
        val openAlumIntent: Intent
        if (Build.VERSION.SDK_INT < 19) {
            openAlumIntent = Intent(Intent.ACTION_GET_CONTENT)
            openAlumIntent.type = "image/*"
        } else
            openAlumIntent =
                Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)

        activity.startActivityForResult(openAlumIntent, requestCode)
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    fun startCropImage(
        activity: Activity,
        uri: Uri,
        requestCode: Int,
        aspectX: Int,
        aspectY: Int,
        outputX: Int,
        outputY: Int
    ) {
        val cropIntent = Intent("com.android.camera.action.CROP")
        //限制图片类型可设置为"image/jpeg" 或者 "image/png"
        cropIntent.setDataAndType(uri, "image/*")
        //设置裁剪
        cropIntent.putExtra("crop", "true")
        //aspectX aspectY 是宽高的比例
        if (aspectX != 0 && aspectY != 0) {
            cropIntent.putExtra("aspectX", 1)
            cropIntent.putExtra("aspectY", 1)
        }
        //outputX outputY 是裁剪图片宽高
        cropIntent.putExtra("outputX", outputX)
        cropIntent.putExtra("outputY", outputY)
        //去除面部检测
        //        cropIntent.putExtra("noFaceDetection", true);
        //是否设置返回值
        cropIntent.putExtra("return-data", true)
        activity.startActivityForResult(cropIntent, requestCode)
    }

    /**
     * 保存图片到相册
     *
     * @param context
     * @param bmp     图片
     */
    fun saveImageToGallery(context: Context, bmp: Bitmap) {
        // 首先保存图片
        val appDir = File(Environment.getExternalStorageDirectory(), "guojijsj")
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        val fileName = "guojijsj_" + System.currentTimeMillis() + ".jpg"
        val file = File(appDir, fileName)
        try {
            val fos = FileOutputStream(file)
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            fos.close()
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        // 其次把文件插入到系统图库
        val path = file.absolutePath
        try {
            MediaStore.Images.Media.insertImage(context.contentResolver, path, fileName, null)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }

        // 最后通知图库更新
        val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val uri = Uri.fromFile(file)
        intent.data = uri
        context.sendBroadcast(intent)
    }

}